package com.talkyun.openx.schema;

import com.talkyun.openx.ocean.proxy.RegistryableProxyFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;

class OpenxReferenceBeanDefinitionParser extends AbstractBeanDefinitionParser {

    @Override
    protected boolean shouldGenerateId() {
        return true;
    }

    @Override
    protected AbstractBeanDefinition parseInternal(Element element, ParserContext ctx) {
        return doMyParse(element);
    }

    private AbstractBeanDefinition doMyParse(Element e) {
        String api = getInterfaceClazz(e);

        BeanDefinitionBuilder builder = rootBeanDefinition(RegistryableProxyFactory.class);
        //        String id = e.hasAttribute("id") ? e.getAttribute("id") : null;
        //        if (id == null || id.trim().equalsIgnoreCase("x")) {
        //            id = api + "-" + ObjectId.get().toString();
        //        }
        //        e.setAttribute("id", id);

        builder.addPropertyValue("interface", api);
        if (e.hasAttribute("id")) {
            builder.addPropertyValue("id", e.getAttribute("id"));
        }
        if (e.hasAttribute("url")) {
            builder.addPropertyValue("url", e.getAttribute("url"));
        }
        if (e.hasAttribute("mapping")) {
            builder.addPropertyValue("mapping", e.getAttribute("mapping"));
        }
        return builder.getBeanDefinition();
    }

    private String getInterfaceClazz(Element element) {
        String clazz = element.getAttribute("interface");
        try {
            Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return clazz;
    }
}